package com.keba.basic.database.plugins;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.keba.basic.encrypt.annotation.Security;
import com.keba.basic.encrypt.handler.CommonSecurityHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.Objects;

/**
 * @author twg
 * @description
 * @date 2025/04/15 15:40
 **/
@Slf4j
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DecryptInterceptor implements Interceptor {


    @Resource
    private CommonSecurityHandler commonSecurityHandler;



    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 1. 执行原方法，获取查询结果
        List<Object> results = (List<Object>) invocation.proceed();
        // 2. 遍历结果对象，解密标记字段
        for (Object result : results) {
            if (result == null) {
                continue;
            }
            Class<?> clazz = result.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Security.class) && String.class.isAssignableFrom(field.getType())) {
                    Object fieldValue = ReflectUtil.getFieldValue(result, field);
                    if (Objects.isNull(fieldValue)) {
                        continue;
                    }
                    ReflectUtil.setFieldValue(result, field, commonSecurityHandler.handleDecrypt(fieldValue.toString()));
                }
            }
        }
        return results;
    }

}
